import React, { Component, Fragment } from "react";
// antd
import { Modal, Table, Button, Col, Pagination, Form, Input, message, Select, Tag } from "antd";
import Action from "@c/buttonAction/Index";
// http
import http from '../../utils/request';

const { Option } = Select;

function ListItem(props) {
    return <Tag color="green">{props.value}</Tag>
}

function ListItem1(props) {
    return <Tag color="blue">{props.value}</Tag>
}

class BusinessManage extends Component {
    constructor(props){
        super(props);
        this.state = {
            // 表格分页
            total: '',
            page: 1,
            page_number: 10,
            dataSource: [],
            columns: [
                {title: "业务线", dataIndex: "name", key: "name"},
                {title: "事业部", dataIndex: "division_name", key: "division_name"},
                {title: "代码", dataIndex: "code", key: "code",
                    render: (text, rowData) => {
                        return (
                            <div className="inline-button">
                                <Action>
                                    <Action.Button>{rowData.code}</Action.Button>
                                </Action>
                            </div>
                        )
                    }
                },
                {title: "运维负责人", dataIndex: "user_business_list", key: "user_business_list", 
                    render: (text, rowData) => {
                        const listItems = rowData.user_business_list.map((item) => 
                                <ListItem key={item.toString()} value={item} />
                        );
                        return (
                            <ul>{listItems}</ul>
                        )
                    }
                },
                {title: "业务负责人", dataIndex: "user_owner_business_list", key: "user_owner_business_list",
                    render: (text, rowData) => {
                        const listItems = rowData.user_owner_business_list.map((item) => 
                                <ListItem1 key={item.toString()} value={item} />
                        );
                        return (
                            <ul>{listItems}</ul>
                        )
                    }
                },
                {title: "运维钉钉组", dataIndex: "business_notifygroup_list", key: "business_notifygroup_list"},
                {title: "业务钉钉组", dataIndex: "business_notifybusinessgroup_list", key: "business_notifybusinessgroup_list"},
                {title: "操作", dataIndex: "operation", key: "operation", 
                    render: (text, rowData) => {
                        return (
                            <div className="inline-button">
                                <Action>
                                    <Action.Button onClick={() => this.onEditBusinessBtn({rowData: rowData, status: true})}>编辑</Action.Button>
                                    <Action.Button onClick={() => this.onDeleteBusinessBtn(rowData)}>删除</Action.Button>
                                </Action>
                            </div>

                        )
                    }           
                }
            ],
            loading: false,
            search_business_name: null,
            visible_add: false,     // 添加
            visible_edit: false,    // 编辑
            visible_delete: false,  // 删除
            business_id: '',
            business_name: '',
            business_msg: '',
            user_list_option: [],
            notifygroup_list_option: [],
            notifybusinessgroup_list_option: [],
            business_user_list_id: false,
            business_user_owner_list_id: false,
            business_notifygroup_list_id: false,
            business_notifybusinessgroup_list_id: false,
            visible_edit_id: '',
            visible_edit_name: '',
            visable_edit_code: '',
            division_list_option: [],
            division_id: '',

        }
        this.formRefAdd = React.createRef();
        this.formRefEdit = React.createRef();
        this.formRefMsg = React.createRef();
    }

    componentDidMount() {
        this.loadData()
        this.loadDataDivision()
    }

    loadData = () => {
        this.setState({
            loading: true
        })
        const requestData = {
            'page': this.state.page,
            'limit': this.state.page_number,
            'name__contains': this.state.search_business_name,
        }

        // 获取分组列表
        http.get('/business', {params: requestData}).then(response=>{
            this.setState({
                dataSource: response.data.data.items,
                total: response.data.data.pages.total,
                loading: false
            })
        }).catch()
    }

    loadDataDivision = () => {
        const requestData = {
            'page': 1,
            'limit': 1000,
        }
        http.get('/division', {params: requestData}).then(response=>{
            const division_list_option = []
            const resp_data = response.data.data.items
            for (let i = 0; i < resp_data.length; i++) {
                division_list_option.push(<Option key={resp_data[i].id}>{resp_data[i].name}</Option>)
            }
            this.setState({
                division_list_option: division_list_option
            })
            console.log('resp_data', resp_data)
        })
    }

    /** 切换每页数量 */
    onChangeSizePage = (page, page_number) => {
        this.setState({
            page: page,
            page_number: page_number,
        }, () => {
            this.loadData()
        })
    }

    /** 业务线搜索 */
    onFinishSearch = (data) => {
        this.setState({
            page: 1,
            search_business_name: data.name ? data.name : null,
        })
        this.loadData()
    }

    /** 添加业务线按钮 */
    onAddBusinessBtn = () => {
        // 获取select用户列表
        http.get('/user_list').then(response=> {
            const data = response.data.data
            const user_list_option = []
            for (let i = 0; i < data.length; i++) {
                user_list_option.push(<Option key={data[i].id}>{data[i].realname}</Option>)
            }
            this.setState({
                user_list_option: user_list_option,
            })
        })

        const requestData = {
            'page': 1,
            'limit': 1000,
        }
        // 获取select运维钉钉群列表
        http.get('/notify/group', {params: requestData}).then(response=> {
            const data = response.data.data.items
            const notifygroup_list_option = []
            for (let i = 0; i < data.length; i++) {
                notifygroup_list_option.push(<Option key={data[i].id}>{data[i].group_title}</Option>)
            }
            this.setState({
                notifygroup_list_option: notifygroup_list_option
            })
        })
        // 获取select业务钉钉群列表
        http.get('/notify/business/group', {params: requestData}).then(response=> {
            const data = response.data.data.items
            const notifybusinessgroup_list_option = []
            for (let i = 0; i < data.length; i++) {
                notifybusinessgroup_list_option.push(<Option key={data[i].id}>{data[i].group_title}</Option>)
            }
            this.setState({
                notifybusinessgroup_list_option: notifybusinessgroup_list_option
            })
        })
        this.setState({
            visible_add: true
        })
    }

    /** 添加业务线取消 */
    onFinishAddCancel = () => {
        this.setState({
            visible_add: false
        })
        this.formRefAdd.current.resetFields()
    }

    /** 添加业务线提交 */
    onFinishAdd = (data) => {
        const requestData = {
            name: data.name,
            code: data.code,
            business_user_list_id: data.business_user_list_id,
            business_user_owner_list_id: data.business_user_owner_list_id,
            business_notifygroup_list_id: data.business_notifygroup_list_id,
            business_notifybusinessgroup_list_id: data.business_notifybusinessgroup_list_id,
            division_id: data.division_id,
        }
        http.post('/business', requestData).then(response=>{
            message.success(response.data.msg)
            this.setState({
                visible_add: false,
            })
            this.formRefAdd.current.resetFields()
            this.loadData()
        }).catch()
    }

    /** 编辑业务线按钮 */
    onEditBusinessBtn = (data) => {
        // 获取业务线已经关联的用户id和钉钉群id
        const p1 = new Promise(resolve=>{
            http.get('/business/' + data.rowData.id).then(response=>{
                resolve(response)
            }).catch()
        })

        const p2 = new Promise(resolve=>{
            // 获取运维钉钉群列表
            const requestData = {
                'page': 1,
                'limit': 1000,
            }
            http.get('/notify/group', {params: requestData}).then(response=> {
                resolve(response)
            })
        })

        const p3 = new Promise(resolve=>{
            // 获取业务钉钉群列表
            const requestData = {
                'page': 1,
                'limit': 1000,
            }
            http.get('/notify/business/group', {params: requestData}).then(response=> {
                resolve(response)
            })
        })

        const p4 = new Promise(resolve=>{
            // 获取用户列表
            http.get('/user_list').then(response=> {
                resolve(response)
            })
        })
        
 
        Promise.all([p1, p2, p3, p4]).then((res)=>{
            const business_notifygroup_list_id = res[0].data.business_notifygroup_list_id
            const business_notifybusinessgroup_list_id = res[0].data.business_notifybusinessgroup_list_id
            const business_user_list_id = res[0].data.business_user_list_id
            const business_user_owner_list_id = res[0].data.business_user_owner_list_id
            const division_id = res[0].data.division_id

            const notifygroup_list_option_data = res[1].data.data.items
            const notifygroup_list_option = []

            const notifybusinessgroup_list_option_data = res[2].data.data.items
            const notifybusinessgroup_list_option = []

            const user_list_option_data = res[3].data.data
            const user_list_option = []

            for (let i = 0; i<notifygroup_list_option_data.length; i++) {
                notifygroup_list_option.push(<Option key={notifygroup_list_option_data[i].id}>{notifygroup_list_option_data[i].group_title}</Option>)
            }

        
            for (let i = 0; i<notifybusinessgroup_list_option_data.length; i++) {
                notifybusinessgroup_list_option.push(<Option key={notifybusinessgroup_list_option_data[i].id}>{notifybusinessgroup_list_option_data[i].group_title}</Option>)
            }

            for (let i = 0; i<user_list_option_data.length; i++) {
                user_list_option.push(<Option key={user_list_option_data[i].id}>{user_list_option_data[i].realname}</Option>)
            }

            this.setState({
                business_notifygroup_list_id: business_notifygroup_list_id,
                business_notifybusinessgroup_list_id: business_notifybusinessgroup_list_id,
                business_user_list_id: business_user_list_id,
                business_user_owner_list_id: business_user_owner_list_id,
                notifygroup_list_option: notifygroup_list_option,
                notifybusinessgroup_list_option: notifybusinessgroup_list_option,
                user_list_option: user_list_option,
                division_id: division_id
            })

            this.formRefEdit.current.setFieldsValue({
                id: data.rowData.id,
                name: data.rowData.name,
                code: data.rowData.code,
                business_user_list_id: this.state.business_user_list_id,
                business_user_owner_list_id: this.state.business_user_owner_list_id,
                business_notifygroup_list_id: this.state.business_notifygroup_list_id,
                business_notifybusinessgroup_list_id: this.state.business_notifybusinessgroup_list_id,
                user_list_option: this.user_list_option,
                notifygroup_list_option: this.state.notifygroup_list_option,
                division_id: division_id
            })
        })
 
        this.setState({
            visible_edit: true,
        })
    }

    /** 编辑业务线取消 */
    onFinishEditCancel = () => {
        this.setState({
            visible_edit: false,
            business_user_list_id: false,
            business_notifygroup_list_id: false,

        })
        this.formRefEdit.current.resetFields();
    }

    /** 编辑业务线提交 */
    onFinishEdit = (data) => {
        const requestData = {
            name: data.name,
            code: data.code,
            business_user_list_id: data.business_user_list_id,
            business_user_owner_list_id: data.business_user_owner_list_id,
            business_notifygroup_list_id: data.business_notifygroup_list_id,
            business_notifybusinessgroup_list_id: data.business_notifybusinessgroup_list_id,
            division_id: data.division_id,
        }
        http.put('/business/' + data.id, requestData).then(response=>{
            message.success(response.data.msg)
            this.setState({
                visible_edit: false
            })
            this.formRefEdit.current.resetFields();
            this.loadData()
        }).catch()
    }

    /** 删除业务线提交 */
    handleBusinessDelete = () => {
        http.delete('/business/' + this.state.business_id).then(response=>{
            message.success(response.data.msg)
            this.setState({
                visible_delete: false,
            })
            this.loadData()
        }).catch()    
    }

    /** 删除业务线提交 */
    onDeleteBusinessBtn = (data) => {
        this.setState({
            business_id: data.id,
            business_name: data.name,
            visible_delete: true
        })
    }

    render(){
        const { loading, dataSource, columns, page, total, visible_add, visible_edit, visible_delete, user_list_option, notifygroup_list_option, 
            notifybusinessgroup_list_option, business_user_list_id, business_notifygroup_list_id, business_notifybusinessgroup_list_id, business_name,
            division_list_option
        } = this.state
        const rowSelection = {
            onChange: this.onCheckbox
        }
        var myStyle = {margin: '20px'}
        var myStyle1 = {margin: '10px', float: 'right'}
        return (
            <Fragment>
                <Form layout="inline" onFinish={this.onFinishSearch}>
                    <Form.Item label="业务线名称" name="name">
                        <Input placeholder="请输入业务线名称"  />
                    </Form.Item>
                    <Form.Item shouldUpdate={true}>
                        <Button type="primary" htmlType="submit">搜索</Button>
                    </Form.Item>
                </Form>
                
                <div style={myStyle1}><Button type="primary" onClick={this.onAddBusinessBtn}>添加业务线</Button></div>
                <Table
                    pagination={false} 
                    rowSelection={rowSelection} 
                    rowKey="id" 
                    columns={columns} 
                    dataSource={dataSource}
                    loading={loading}
                    scroll={{ y: 500, x: '70vw' }}
                >
                </Table>

                <div style={myStyle}>
                    <Col span={16}>
                        <Pagination
                            onChange={this.onChangeSizePage}
                            current={page}
                            total={total}
                            showSizeChanger
                            showQuickJumper
                            showTotal={total => `Total ${total} items`}
                        />
                    </Col>
                </div>

                <Modal
                    title="添加业务线"
                    visible={visible_add}
                    onCancel={this.onFinishAddCancel}
                    okText="确认"
                    cancelText="取消"
                    footer={null}
                >
                    <Form
                        onFinish={this.onFinishAdd}
                        ref={this.formRefAdd}
                        labelCol={{ span: 5 }}
                        wrapperCol={{ span: 14 }}
                    >
                        <Form.Item label="业务线名称" name="name">
                            <Input></Input>
                        </Form.Item>
                        <Form.Item label="业务线代码" name="code">
                            <Input></Input>
                        </Form.Item>
                        <Form.Item label="运维负责人" name="business_user_list_id">
                            <Select
                                mode="multiple"
                                allowClear
                                showSearch
                                style={{ width: '100%' }}
                                placeholder="Please select"
                                >
                                {user_list_option}
                            </Select>
                        </Form.Item>
                        <Form.Item label="运维钉钉群" name="business_notifygroup_list_id">
                            <Select
                                mode="multiple"
                                allowClear
                                showSearch
                                style={{ width: '100%' }}
                                placeholder="Please select"
                                >
                                {notifygroup_list_option}
                            </Select>
                        </Form.Item>
                        <Form.Item label="业务负责人" name="business_user_owner_list_id">
                            <Select
                                mode="multiple"
                                allowClear
                                showSearch
                                style={{ width: '100%' }}
                                placeholder="Please select"
                                >
                                {user_list_option}
                            </Select>
                        </Form.Item>
                        <Form.Item label="业务钉钉群" name="business_notifybusinessgroup_list_id">
                            <Select
                                mode="multiple"
                                allowClear
                                showSearch
                                style={{ width: '100%' }}
                                placeholder="Please select"
                                >
                                {notifybusinessgroup_list_option}
                            </Select>
                        </Form.Item>

                        <Form.Item label="业务事业部" name="division_id" rules={[{ required: true}]}>
                            <Select
                                allowClear
                                showSearch
                                style={{ width: '100%' }}
                                placeholder="Please select"
                                >
                                {division_list_option}
                            </Select>
                        </Form.Item>

                        <Form.Item>
                            <Button htmlType="submit" type="primary">确定</Button>
                        </Form.Item>                                                               
                    </Form>           
                </Modal>

                { (business_user_list_id.length >=0 && business_notifygroup_list_id.length >=0 && business_notifybusinessgroup_list_id.length >=0) && (
                <Modal
                    title="编辑业务线"
                    visible={visible_edit}
                    onCancel={this.onFinishEditCancel}
                    okText="确认"
                    cancelText="取消"
                    footer={null}
                >
                    <Form
                        onFinish={this.onFinishEdit}
                        ref={this.formRefEdit}
                        labelCol={{ span: 5 }}
                        wrapperCol={{ span: 14 }}
                    >
                        <Form.Item label="业务线ID" name="id" hidden>
                            <Input ></Input>
                        </Form.Item>
                        <Form.Item label="业务线名称" name="name">
                            <Input disabled></Input>
                        </Form.Item>
                        <Form.Item label="业务线代码" name="code">
                            <Input disabled></Input>
                        </Form.Item>
                        <Form.Item label="运维负责人" name="business_user_list_id">
                            <Select
                                mode="multiple"
                                allowClear
                                style={{ width: '100%' }}
                                placeholder="Please select"
                                optionFilterProp="children"
                                >
                                {user_list_option}
                            </Select>
                        </Form.Item>

                        <Form.Item label="运维钉钉群" name="business_notifygroup_list_id">
                            <Select
                                mode="multiple"
                                allowClear
                                style={{ width: '100%' }}
                                placeholder="Please select"
                                optionFilterProp="children"
                                >
                                {notifygroup_list_option}
                            </Select>
                        </Form.Item>

                        <Form.Item label="业务负责人" name="business_user_owner_list_id">
                            <Select
                                mode="multiple"
                                allowClear
                                style={{ width: '100%' }}
                                placeholder="Please select"
                                optionFilterProp="children"
                                >
                                {user_list_option}
                            </Select>
                        </Form.Item>

                        <Form.Item label="业务钉钉群" name="business_notifybusinessgroup_list_id">
                            <Select
                                mode="multiple"
                                allowClear
                                style={{ width: '100%' }}
                                placeholder="Please select"
                                optionFilterProp="children"
                                >
                                {notifybusinessgroup_list_option}
                            </Select>
                        </Form.Item>

                        <Form.Item label="业务事业部" name="division_id" rules={[{ required: true}]}>
                            <Select
                                allowClear
                                showSearch
                                style={{ width: '100%' }}
                                placeholder="Please select"
                                >
                                {division_list_option}
                            </Select>
                        </Form.Item>

                        <Form.Item>
                            <Button htmlType="submit" type="primary">确定</Button>
                        </Form.Item>                                                               
                    </Form>           
                </Modal>
                )}

                <Modal
                    title="删除业务线"
                    visible={visible_delete}
                    onOk={this.handleBusinessDelete}
                    onCancel={() => {this.setState({visible_delete: false, business_id: ''})}}
                    okText="确认"
                    cancelText="取消"
                >
                    <p>确定删除业务线<span style={{color: 'red'}}> {business_name}</span>? 删除后将无法恢复</p>
                </Modal>
            </Fragment>
        )
    }
}
export default BusinessManage;